/*
 * @Author: fisher
 * @Date: 2024-03-04 10:40:52
 * @LastEditors: fisher luthor-li@qq.com
 * @LastEditTime: 2024-03-04 16:39:58
 * @FilePath: \allback\utils\ueClient.js
 * @Description:
 */

const UeInstance = require('../models/ueinstanceModel') // 导入你的Mongoose模型
const axios = require('axios')
async function addUserConnection(instanceId, connectData) {
  const instance = await UeInstance.findById(instanceId)

  if (instance) {
    instance.connections.push(connectData) // 将新连接添加到数组
    instance.connectStatus = instance.connections.length > 0 ? true : false // 实时更新状态
    const data = await instance.save() // 保存到数据库
    return data
  }
}
async function removeUserConnection(instanceId, userId) {
  const instance = await UeInstance.findById(instanceId)

  if (instance) {
    instance.connections = instance.connections.filter(
      conn => conn.userId.toString() !== userId
    )
    instance.connectStatus = instance.connections.length > 0 ? true : false
    const data = await instance.save()
    return data
  }
}

const callSignalCloseClient = (instanceId, connectData) => {
  let url = ''
  if (!connectData.useHttps) {
    url = `http://${connectData.signalHost}:${connectData.signalPort}/closeClient`
  } else {
    url = `https://${connectData.signalHost}:${connectData.signalPort}/closeClient`
  }
  console.log('url', url)
  console.log('instanceId', instanceId)
  console.log('connectData.playerId', connectData.playerId)
  return axios.post(url, {
    instanceId,
    playerId: connectData.playerId
  })
}
module.exports = {
  addUserConnection,
  removeUserConnection,
  callSignalCloseClient
}
